package com.company.tree;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @author jrue
 * @version 1.0
 * @date 2020/1/28 14:44
 * https://leetcode-cn.com/problems/n-ary-tree-postorder-traversal/
 *给定一个 N 叉树，返回其节点值的后序遍历。
 */
public class NAryTreePostorderTraversal {

    List<Integer> list = new ArrayList<>();
    public List<Integer> postorder(Node root) {
        if (root != null) {
            for (int i = 0; i < root.children.size(); i++) {
                postorder(root.children.get(i));
            }
            list.add(root.val);
        }
        return list;
    }

    public List<Integer> postorder01(Node root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) return list;
        Stack<Node> stack01 = new Stack<>();
        Stack<Node> stack02 = new Stack<>();

        stack01.push(root);
        while (!stack01.isEmpty()) {
            Node node = stack01.pop();
            stack02.push(node);
            for (int i = 0; i < node.children.size(); i++) {
                stack01.push(node.children.get(i));
            }
        }

        while (!stack02.isEmpty()) {
            list.add(stack02.pop().val);
        }

        return list;
    }
}
